/// <reference path="../node_modules/chrome-extension-async/chrome-extension-async.d.ts" />
import 'chrome-extension-async'
import Message from './interfaces/Message'
import { MSG_TYPE } from './interfaces/Message'
import { isNull } from './functions'

const STORAGE_KEY_VOLUME = 'chrome-volume-manager-value'

const listenerHandlers = {}
listenerHandlers[MSG_TYPE.GET_STORAGE_VOLUME] = function(request: Message, sender, sendResponse) {
  let volumeLevel = parseFloat(localStorage.getItem(STORAGE_KEY_VOLUME))
  volumeLevel = isNull(volumeLevel) ? null : volumeLevel
  const message: Message = { name: MSG_TYPE.GET_STORAGE_VOLUME, value: volumeLevel }
  sendResponse(message)
  return true
}

listenerHandlers[MSG_TYPE.SET_STORAGE_VOLUME] = function(request: Message, sender, sendResponse) {
  sendResponse(undefined)
  if(request.name === MSG_TYPE.SET_STORAGE_VOLUME) {
    localStorage.setItem(STORAGE_KEY_VOLUME, String(request.value))
  }
  return true
}

chrome.runtime.onMessage.addListener((request: Message, sender, sendResponse) => {
  const listenerHandler = listenerHandlers[request.name]
  if(typeof listenerHandler != 'undefined') {
    listenerHandler(request, sender, sendResponse)
  }
  return true
})
